<?php
/**
 * Class MpWeixinHome
 * Desc  微信小程序首页
 * Create on 2021/9/15 14:03
 * Create by wangyafang
 */

namespace app\api\controller\xyb;


use addons\xyb\XypHelper;
use app\api\model\xyb\AgentServerView;
use app\api\model\xyb\Carousel;
use app\api\service\OrdersService;
use app\api\service\UsersService;
use think\Db;
use app\api\model\xyb\Advertise;
use app\api\model\xyb\Server;
use app\api\model\xyb\Order;
use app\api\controller\xyb\Server as ServerController;

class MpWeixinHome extends Base
{
    protected $noNeedLogin = [''];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];


    public function hall(){
        $tab = $this->request->param('tab','all');
        $status = $this->request->param('status', '');
        $data = [];
        switch ($tab){
            case 'all':
                $data = $this->all_order($status);
                break;
            case 'pending':
                $data = $this->task_hall();
                break;
            case 'push':
                $data = $this->my_push($status);
                break;
            case 'help':
                $data = $this->my_help($status);
                break;

        }
        $this->success('请求成功', $data);
    }

    public function all_order($status){
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $users = $this->getAuthUsers();
        if(!$users_agent = UsersService::getCommunityWhereUsersLocated($users->id)){
            return ['total'=>0,'data'=>[]];
        }
        $where = ['agent_id'=>$users_agent->agent_id];
        $orderModel = new Order();
        $param = $this->request->param();
        $user_id = $users->id;
        if(request()->param('dd')){
            $count = $orderModel->where($where)->where(function ($query)use($user_id, $status){
                $query->where(function ($query_one)use($user_id, $status){
                    $query_one->where('user_id', $user_id);
                    if($status >= 0){
                        $query_one->where('status', $status);
                    } else {
                        $query_one->where('status', '>=', '0');
                    }
                });
                if($status != 0){
                    $query->whereOr(function ($query_two)use($user_id, $status){
                        $query_two->where('user_id', '<>', $user_id);
                        if($status >= 0){
                            $query_two->where('status', $status);
                        } else {
                            $query_two->whereIn('status', [1, 2, 3, 7, 8]);
                        }
                    });
                }
            })->fetchSql()->count();
            var_dump($count);exit;
        }
        $count = $orderModel->where($where)->where(function ($query)use($user_id, $status){
            $query->where(function ($query_one)use($user_id, $status){
                $query_one->where('user_id', $user_id);
                if($status >= 0){
                    $query_one->where('status', $status);
                } else {
                    $query_one->where('status', '>=', '0');
                }
            });
            if($status != 0){
                $query->whereOr(function ($query_two)use($user_id, $status){
                    $query_two->where('user_id', '<>', $user_id);
                    if($status >= 0){
                        $query_two->where('status', $status);
                    } else {
                        $query_two->whereIn('status', [1, 2, 3, 7, 8]);
                    }
                });
            }
        })->count();

        $data = $orderModel->where($where)->where(function ($query)use($user_id, $status){
            $query->where(function ($query_one)use($user_id, $status){
                $query_one->where('user_id', $user_id);
                if($status >= 0){
                    $query_one->where('status', $status);
                } else {
                    $query_one->where('status', '>=', '0');
                }
            });
            if($status != 0){
                $query->whereOr(function ($query_two)use($user_id, $status){
                    $query_two->where('user_id', '<>', $user_id);
                    if($status >= 0){
                        $query_two->where('status', $status);
                    } else {
                        $query_two->whereIn('status', [1, 2, 3, 7, 8]);
                    }
                });
            }
        })->alias('order')
            ->order('id desc')
            ->page($param['page'], $param['limit'])
            ->with(['user'])
            ->field("order.id,order.information,order.start,order.destination,order.hope_arrive,order.express,order.receive_id,
            order.type,total_fee,createtime,user_id,agent_id,status")
            ->select();

        foreach ($data as $k=>$v) {
            $data[$k]['dateline_create_date'] = XypHelper::xyb_dateline($v['createtime']);//创建时间
            $data[$k]['receive_users'] = new \ArrayObject();
            $push_users = UsersService::getUsersFoundation($v['user_id']);
            $data[$k]['nickname'] = $push_users['nickname'];
            $data[$k]['avatar'] = $push_users['avatar'];
            $data[$k]['is_see_show'] = false;
            if($v['user_id'] == $users->id || ($v['receive_id'] == $users->id)){
                $data[$k]['is_see_show'] = true;
            }
            if($v['receive_id']){
                $data[$k]['receive_users'] = UsersService::getReceivingUsersFoundation($v['receive_id'], $v['agent_id']);
            }
            $data[$k]['income'] = OrdersService::CalculateOrdersRevenueProportion($v['total_fee'], $v['agent_id'], $v['type']);
            $data[$k]['status_text'] = OrdersService::formatOrdersStatus($v['status']);
        }
        return ['total'=>$count,'data'=>$data];
    }

    public function task_hall(){
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $users = $this->getAuthUsers();
        if(!$users_agent = UsersService::getCommunityWhereUsersLocated($users->id)){
            return ['total'=>0,'data'=>[]];
        }
        if(!$users_agent->is_rider){
            return ['total'=>0,'data'=>[]];
        }
        if(!$users_agent->is_rider || !$users_agent->rider_info){
            return ['total'=>0,'data'=>[]];
        }
//        if(!isset($users_agent->is_rider_stated) || !$users_agent->is_rider_stated){
//            return ['total'=>0,'data'=>[]];
//        }
//        if(!isset($users_agent->is_rider_receiving) || !$users_agent->is_rider_receiving){
//            return ['total'=>0,'data'=>[]];
//        }
        $where = ['agent_id'=>$users_agent->agent_id];
        $orderModel = new Order();
        $param = $this->request->param();
        $map['status'] = 1;
        $count = $orderModel->where($where)->where($map)->count();
        $data = $orderModel->where($where)
            ->where($map)
            ->alias('order')
            ->order('id desc')
            ->page($param['page'],$param['limit'])
            ->with(['user'])
            ->field("order.id,order.information,order.start,order.destination,order.hope_arrive,order.express,order.receive_id,
            receive_limit,order.type,total_fee,createtime,type,user_id,agent_id,status,order.total_fee as price")//total_fee as price订单金额
            ->select();

        foreach ($data as $k=>$v) {
            $data[$k]['dateline_create_date'] = XypHelper::xyb_dateline($v['createtime']);//创建时间
            $data[$k]['receive_users'] = new \ArrayObject();
            $push_users = UsersService::getUsersFoundation($v['user_id']);
            $data[$k]['nickname'] = $push_users['nickname'];
            $data[$k]['avatar'] = $push_users['avatar'];
            $data[$k]['is_see_show'] = true;
//            if($v['user_id'] == $users->id || ($v['receive_id'] == $users->id)){
//                $data[$k]['is_see_show'] = true;
//            }
            if($v['receive_id']){
                $data[$k]['receive_users'] = UsersService::getReceivingUsersFoundation($v['receive_id'],$v['agent_id']);
            }
            $data[$k]['income'] = OrdersService::CalculateOrdersRevenueProportion($v['total_fee'], $v['agent_id'], $v['type']);
            $data[$k]['status_text'] = OrdersService::formatOrdersStatus($v['status']);
        }
        return ['total'=>$count,'data'=>$data];
    }

    public function my_help($status){
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $users = $this->getAuthUsers();
        if(!$users_agent = UsersService::getCommunityWhereUsersLocated($users->id)){
            return ['total'=>0,'data'=>[]];
        }
        $where = ['agent_id'=>$users_agent->agent_id];
        $orderModel = new Order();
        $param = $this->request->param();
        $map['receive_id'] = $users->id;
        if($status > 0){
            $map['status'] = $status;
        } else {
            $map['status'] = array('in',[2, 3, 7, 8]);
        }
        $count = $orderModel->where($where)->where($map)->count();
        $data = $orderModel->where($where)
            ->where($map)
            ->alias('order')
            ->order('id desc')
            ->page($param['page'], $param['limit'])
            ->with(['user'])
            ->field("order.id,order.information,order.start,order.destination,order.hope_arrive,order.express,order.receive_id,
            receive_limit,order.type,total_fee,createtime,type,user_id,agent_id,status,order.total_fee as price")//total_fee as price订单金额
            ->select();

        foreach ($data as $k=>$v) {
            $data[$k]['dateline_create_date'] = XypHelper::xyb_dateline($v['createtime']);//创建时间
            $data[$k]['receive_users'] = new \ArrayObject();
            $push_users = UsersService::getUsersFoundation($v['user_id']);
            $data[$k]['nickname'] = $push_users['nickname'];
            $data[$k]['avatar'] = $push_users['avatar'];
            $data[$k]['is_see_show'] = true;

            if($v['receive_id']){
                $data[$k]['receive_users'] = UsersService::getReceivingUsersFoundation($v['receive_id'], $v['agent_id']);
            }
            $data[$k]['income'] = OrdersService::CalculateOrdersRevenueProportion($v['total_fee'], $v['agent_id'], $v['type']);
            $data[$k]['status_text'] = OrdersService::formatOrdersStatus($v['status']);
        }
        return ['total'=>$count,'data'=>$data];
    }

    public function my_push($status){
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $users = $this->getAuthUsers();
        if(!$users_agent = UsersService::getCommunityWhereUsersLocated($users->id)){
            return ['total'=>0,'data'=>[]];
        }
        $where = ['agent_id'=>$users_agent->agent_id];
        $orderModel = new Order();
        $param = $this->request->param();
        $map['user_id'] = $users->id;
        if($status >= 0){
            $map['status'] = $status;
        } else {
            $map['status'] = array('in',[0, 1, 2, 3, 7, 8]);
        }
        $count = $orderModel->where($where)->where($map)->count();
        $data = $orderModel->where($where)
            ->where($map)
            ->alias('order')
            ->order('id desc')
            ->page($param['page'], $param['limit'])
            ->with(['user'])
            ->field("order.id,order.information,order.start,order.destination,order.hope_arrive,order.express,order.receive_id,
            receive_limit,order.type,total_fee,createtime,type,user_id,agent_id,status,order.total_fee as price")//total_fee as price订单金额
            ->select();

        foreach ($data as $k=>$v) {
            $data[$k]['dateline_create_date'] = XypHelper::xyb_dateline($v['createtime']);//创建时间
            $data[$k]['receive_users'] = new \ArrayObject();
            $push_users = UsersService::getUsersFoundation($v['user_id']);
            $data[$k]['nickname'] = $push_users['nickname'];
            $data[$k]['avatar'] = $push_users['avatar'];
            $data[$k]['is_see_show'] = true;
            if($v['receive_id']){
                $data[$k]['receive_users'] = UsersService::getReceivingUsersFoundation($v['receive_id'], $v['agent_id']);
            }
            $data[$k]['income'] = OrdersService::CalculateOrdersRevenueProportion($v['total_fee'], $v['agent_id'], $v['type']);
            $data[$k]['status_text'] = OrdersService::formatOrdersStatus($v['status']);
        }
        return ['total'=>$count,'data'=>$data];
    }

    public function index()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        /*轮播*/
        $carouselModel = new Carousel();
        $agent_id = $this->request->param('agent_id');
        $where['status'] = array('eq','normal');
        $carousel_list = $carouselModel
            ->where($where)
            ->where('agent_id',$agent_id)
            ->whereor('agent_id','-1')
            ->order('agent_id asc,weigh desc,id desc')
            ->field('id,image,jump_method as mode,value,info')
            ->select();
        foreach ($carousel_list as $k=>$v) {
            $carousel_list[$k]['url'] = array(
                'mode'=>$v['mode'],
                'path'=>$v['value'],
                'info'=>$v['info'],
            );
            unset($carousel_list[$k]['mode']);
            unset($carousel_list[$k]['value']);
            unset($carousel_list[$k]['info']);
        }

        /*服务列表*/

        $agent_where['agent_id'] = array('eq',$agent_id);
        $serverModel = new Server();
        $server_list = $serverModel->where($where)->where($agent_where)
            ->where('status','normal')
            ->order('weigh desc,id desc')
            ->field('id,server_name,icon_image')
            ->select();
        //todo wangyafang 服务path暂时写死
        foreach ($server_list as $k=>$v) {
            switch ($v['server_name']) {
                case '校园跑腿':
                    $server_list[$k]['url'] = array(
                        'mode'=>2,
                        'path'=>'/pages/Component/Module/Campus/Program/Runerrands/index/index?type=1',
                        'info'=>$v['server_name'],
                    );
                    break;
                case '快递代取':
                    $server_list[$k]['url'] = array(
                        'mode'=>2,
                        'path'=>'/pages/Component/Module/Campus/Program/Runerrands/index/index?type=2',
                        'info'=>$v['server_name'],
                    );
                    break;
                case '租借服务':
                    $server_list[$k]['url'] = array(
                        'mode'=>2,
                        'path'=>'/pages/Component/Module/Campus/Program/Runerrands/index/index?type=4',
                        'info'=>$v['server_name'],
                    );
                    break;
            }
            if ($v['icon_image'] == ''){
                $server_list[$k]['icon_image'] = XypHelper::xyb_full_url('/assets/addons/xyb/img/icon.png');
            }
        }

        /*广告列表*/
        $advertiseModel = new Advertise();
        $advertise_list = $advertiseModel
            ->where($where)
            ->where('agent_id',$agent_id)
            ->whereor('agent_id','-1')
            ->order('agent_id asc,weigh desc,id desc')
            ->field('id,image,jump_method as mode,value,info')
            ->select();
        foreach ($advertise_list as $k=>$v) {
            $advertise_list[$k]['url'] = array(
                'mode'=>$v['mode'],
                'path'=>$v['value'],
                'info'=>$v['info'],
            );
            unset($advertise_list[$k]['mode']);
            unset($advertise_list[$k]['value']);
            unset($advertise_list[$k]['info']);
        }

        $data = [
            'carousel_list'=>$carousel_list,
            'notice_title'=>$this->configObj->notice_title,
            'notice_content'=>$this->configObj->notice_content,
            'server_list'=>$server_list,
            'apply_receive_image'=>XypHelper::xyb_full_url($this->configObj->apply_receive_image),
            'apply_receive_image_show'=>$this->configObj->apply_receive_image_show,
            'advertise_list'=>$advertise_list,
        ];
        $this->success('请求成功',$data);
    }

    /*服务显示列表*/
    public function server_view_list()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $where['status'] = array('eq','normal');
        $agent_id = $this->request->param('agent_id');
        $agent_where['agent_id'] = array('eq',$agent_id);
        /*服务显示*/
        $agentServerViewModel = new AgentServerView();
        $server_view_list = $agentServerViewModel->where($where)->where($agent_where)
            ->order('weigh desc,id desc')
            ->field('id,server_name')
            ->select();
        $this->success('请求成功',$server_view_list);
    }

    /*
     * desc：接单列表/超市外卖/校园论坛数据
     * */
    public function server_list()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $param = $this->request->param();
        if(isset($param['order_type']) && $param['order_type']) {//任务大厅服务列表
            $this->order_home([
                'agent_id'=>$param['agent_id'],
                'type'=>$param['order_type'],
            ]);
        } else {//首页接单列表数据
            $this->order_home([
                'agent_id'=>$param['agent_id'],
            ]);
        }
    }

    /*接单列表*/
    public function order($where = [])
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $orderModel = new Order();
        $param = $this->request->param();
        $count = $orderModel->where($where)->count();
        $data = $orderModel->where($where)
            ->alias('order')
            ->order('id desc')
            ->page($param['page'],$param['limit'])
            ->with(['user'])
            ->field("order.id,order.information,order.start,order.destination,order.hope_arrive,order.express,
            game_platform,game_time,receive_limit,
            lease_duration,
            total_fee,createtime,type,user_id,agent_id")
            ->select();
        $serverController = new ServerController();
        $app_plat = $this->request->param('app_plat');
        foreach ($data as $k=>$v) {
            unset($data[$k]['down_method_text']);
            $data[$k]['time'] = XypHelper::xyb_dateline($v['createtime']);
            $data[$k]['total_fee'] = $serverController->get_receive_profit($v);
            switch ($app_plat) {
                case 'MP-WEIXIN':
                    $wechatInfo = Db::name('xyb_user_plat')
                        ->alias('u_p')
                        ->where('u_p.user_id',$v['user_id'])
                        ->join('xyb_user_wechat u_w','u_w.id = u_p.wechat_id')
                        ->field('u_w.nickname,u_w.avatar')
                        ->find();
                    $data[$k]['nickname'] = $wechatInfo['nickname'];
                    $data[$k]['avatar'] = XypHelper::xyb_full_url($wechatInfo['avatar']);
                    break;
            }
            if($v['type'] == 2) {
                $data[$k]['information'] = '';
            }
        }
        $this->success('请求成功', ['total'=>$count,'data'=>$data]);
    }

    /*首页接单列表*/
    public function order_home($where = [])
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $orderModel = new Order();
        $param = $this->request->param();
        $map['status'] = array('in',[1,2,3,7]);
        $count = $orderModel->where($where)->where($map)->count();
        $data = $orderModel->where($where)
            ->where($map)
            ->alias('order')
            ->order('id desc')
            ->page($param['page'],$param['limit'])
            ->with(['user'])
            ->field("order.id,order.information,order.start,order.destination,order.hope_arrive,order.express,
            game_platform,game_time,receive_limit,
            lease_duration,
            total_fee,createtime,type,user_id,agent_id,status,order.total_fee as price")//total_fee as price订单金额
            ->select();
        $serverController = new ServerController();
        foreach ($data as $k=>$v) {
            unset($data[$k]['down_method_text']);
            $data[$k]['time'] = XypHelper::xyb_dateline($v['createtime']);
            $data[$k]['total_fee'] = $serverController->get_receive_profit($v);//预估收益
            $wechatInfo = Db::name('xyb_user_plat')
                ->alias('u_p')
                ->where('u_p.user_id',$v['user_id'])
                ->join('xyb_user_wechat u_w','u_w.id = u_p.wechat_id')
                ->field('u_w.nickname,u_w.avatar')
                ->find();
            $data[$k]['nickname'] = $wechatInfo['nickname'];
            $data[$k]['avatar'] = XypHelper::xyb_full_url($wechatInfo['avatar']);
            if($v['type'] == 2) {
                $data[$k]['information'] = '';
            }
        }
        $this->success('请求成功', ['total'=>$count,'data'=>$data]);
    }
}